package com.neo.shiro.session;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import com.neo.utils.SerializeUtils;

@Component
public class MySessionDAO extends EnterpriseCacheSessionDAO {

	    private static Logger logger = LoggerFactory.getLogger(MySessionDAO.class);

	    // session 在redis过期时间是30分钟30*60
	    private static int expireTime = 1800;

	    private static String prefix = "shirosession:";

	    @Autowired
	    private StringRedisTemplate stringRedisTemplate;

	    // 创建session，保存到数据库
	    @Override
	    protected Serializable doCreate(Session session) {
	        Serializable sessionId = super.doCreate(session);
	        logger.debug("==>创建session:[{}]", session.getId());
	        String value = SerializeUtils.serializeToString((SimpleSession)session);
	        stringRedisTemplate.opsForValue().set(prefix + sessionId.toString(), value);
	        return sessionId;
	    }

	    // 获取session
	    @Override
	    protected Session doReadSession(Serializable sessionId) {
	        logger.debug("==>获取session sessionId:[{}]", sessionId);
	        // 先从缓存中获取session，如果没有再去数据库中获取
	        Session session = getCachedSession(sessionId);
	        if (session == null) {
	            String value = stringRedisTemplate.opsForValue().get(prefix );
	            session = SerializeUtils.dserializeToObject(value);
	            logger.debug("==>session状态:[{}]", session);
	        }
	        return session;
	    }

	    // 更新session的最后一次访问时间
	    @Override
	    protected void doUpdate(Session session) {
	        super.doUpdate(session);
	        logger.debug("==>更新session:[{}]", session.getId());
	        String key = prefix + session.getId().toString();
	        if (!stringRedisTemplate.hasKey(key)) {
	        	String value = SerializeUtils.serializeToString((SimpleSession)session);
	        	stringRedisTemplate.opsForValue().set(key, value);
	            logger.debug("==>写入redis session:[{}]", session);
	        }
	        stringRedisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
	    }

	    // 删除session
	    @Override
	    protected void doDelete(Session session) {
	        logger.debug("==>删除session:[{}]", session.getId());
	        super.doDelete(session);
	        stringRedisTemplate.delete(prefix + session.getId().toString());
	    }
}
